package com.shinektv.heartbeat;

import android.text.TextUtils;
import android.util.Log;

import com.shinektv.utils.SystemUtil;
import com.shinektv.utils.TimeCounter;

import org.json.JSONObject;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author wk
 * @date 2024/12/3 14:00
 * @describe
 */
public class HeartBeatClient {
    private static HeartBeatClient instance;
    private static final String TAG = "KSClient";
    private LocalClientSocketCommon mLocalClientSocketCommon = null;

    public static HeartBeatClient getInstance() {

        if (instance == null) {
            synchronized (HeartBeatClient.class) {
                if (instance == null) {
                    instance = new HeartBeatClient();
                }
            }
        }
        return instance;
    }

    private volatile boolean mInit = false;

    private String mStartTime = "";
    private int mServiceType = 30;

    private TimeCounter mTimeCounter = new TimeCounter();

    /**
     * 初始化,只调用一次
     */
    public void init() {
        init("ksstore");
    }

    public void init(String socketName) {
        init(socketName, 30);
    }

    /**
     * 初始化,只调用一次
     */
    public void init(String socketName, int type) {
        if (mInit) return;
        mServiceType = type;
        mTimeCounter.start();
        mInit = true;
        mStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) ;

        synchronized (HeartBeatClient.class) {

            if (mLocalClientSocketCommon != null) return;

            if (mLocalClientSocketCommon == null) {
                mLocalClientSocketCommon = new LocalClientSocketCommon();
            }
            mLocalClientSocketCommon.init(socketName, new LocalClientSocketCommon.SocketListener() {
                @Override
                public void onConnect() {
                    Log.i(TAG, "onConnect: ");
                }

                @Override
                public void onReceiveMessage(String msg) {
                    Log.i(TAG, "onReceiveMessage: ");
                }

                @Override
                public void onDisconnect() {
                    Log.i(TAG, "onDisconnect: ");
                }
            });
            startReportTask();
        }
    }


    private String mLocalIp = "";
    private String mMac = "";
    DatagramSocket udpSocket = null;
    InetAddress mInetAddress = null;

    /**
     * 开始运行上报信息,每10S上传一次
     */
    private void startReportTask() {

        new Thread(new Runnable() {
            @Override
            public void run() {

                String sendStr = "";
                while (true) {
                    updateInfo();
                    sendStr = getSendReprotData();
                    sendData(sendStr);
                    try {
                        Thread.sleep(10 * 1000);
                    } catch (InterruptedException e) {
                        Log.w(TAG, "startReportTask: " + e.getMessage());
                    }
                }
            }
        }).start();

    }

    private void updateInfo() {
        try {
            if (TextUtils.isEmpty(mLocalIp)) {
                mLocalIp = SystemUtil.getActiveIpAddress();
            }

            if (TextUtils.isEmpty(mMac)) {
                mMac = SystemUtil.getMac();
            }
        } catch (Exception e) {
            Log.w(TAG, "updateInfo: " + e.getMessage());
        }
    }

    private String getSendReprotData() {

        try {
            JSONObject root = new JSONObject();
            root.put("cmd", "service_heart");
            JSONObject content = new JSONObject();
            content.put("type", mServiceType);
            content.put("host_ip", mLocalIp);
            content.put("host_name", mMac);
            content.put("start_time", mStartTime);
            content.put("run_duration", mTimeCounter.duration_seconds() + "");
            content.put("mac", mMac);
            root.put("content", content);
            return root.toString();

        } catch (Exception e) {

            Log.e(TAG, "sendReprotData: " + e.getMessage());
        }
        return "";
    }

    private void sendData(String data) {
        try {
            if (TextUtils.isEmpty(data)) return;
            if (udpSocket == null) {
                udpSocket = new DatagramSocket();
            }

            if (mInetAddress == null) {
                mInetAddress = InetAddress.getByName("127.0.0.1");
            }

            byte[] sendData = data.getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, mInetAddress, 29001);

            if (udpSocket != null) {
                udpSocket.send(datagramPacket);
            }
            datagramPacket = null;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
